package com.jxb.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.EventExecutorGroup;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;

public class NettyRemotingServer {

    private final int port;

    private final String serverName;

    protected final HashMap<Integer/* request code */, Pair<NettyRequestProcessor, ExecutorService>> processorTable =
            new HashMap<Integer, Pair<NettyRequestProcessor, ExecutorService>>(64);

    public Pair<NettyRequestProcessor, ExecutorService> defaultRequestProcessor;

    public NettyRemotingServer(int port, String serverName) {
        this.port = port;
        this.serverName = serverName;
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyRemotingServer(9876,"").start();
    }

    public void start() throws InterruptedException {
        //线程组
        //默认线程数为逻辑核数的2倍
        NioEventLoopGroup group = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup(10);
//        EpollEventLoopGroup group1 = new EpollEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
//            b.group(group,work)
            b.group(group)
                    .channel(NioServerSocketChannel.class)
//                    .childOption(ChannelOption.ALLOCATOR)
//                    .channel(EpollServerSocketChannel.class)
                    .localAddress(new InetSocketAddress(port))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyEncoder())
                                    .addLast(new NettyDecoder())
                                    .addLast(new IdleStateHandler(0, 0, 120))
                                    .addLast(new EchoServerHandler());
                        }
                    });
            ChannelFuture sync = b.bind().sync();
            System.out.println(serverName);
            sync.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }
    }

    private class EchoServerHandler extends SimpleChannelInboundHandler<RemotingCommand> {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, RemotingCommand msg) throws Exception {
            processMessageReceived(ctx, msg);
//            ctx.close();//短链接
        }

        //tcp三次握手之后，会执行该方法
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("连接已建立");
            super.channelActive(ctx);
        }

        //异常触发
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }

    private void processMessageReceived(ChannelHandlerContext ctx, RemotingCommand msg) {
        final RemotingCommand cmd = msg;
        if (cmd != null) {
            switch (cmd.getType()) {
                case REQUEST_COMMAND:
                    processRequestCommand(ctx, cmd);
                    break;
                case RESPONSE_COMMAND:
//                    processResponseCommand(ctx, cmd);
                    break;
                default:
                    break;
            }
        }
    }

    private void processRequestCommand(ChannelHandlerContext ctx, RemotingCommand cmd) {
        final Pair<NettyRequestProcessor, ExecutorService> matched = this.processorTable.get(cmd.getCode());
        final Pair<NettyRequestProcessor, ExecutorService> pair = null == matched ? this.defaultRequestProcessor : matched;
        final int opaque = cmd.getOpaque();
        if (pair != null) {
            Runnable run = new Runnable() {
                @Override
                public void run() {
                    NettyRequestProcessor processor = pair.getObject1();
                    try {
                        RemotingCommand response = processor.processRequest(ctx, cmd);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            RequestTask requestTask = new RequestTask(run, ctx.channel(), cmd);
            pair.getObject2().submit(requestTask);
        }
    }

}
